import java.io.*;
import java.net.*;
import java.util.*;

public class ConnectionProcessor implements Runnable
{
  private EM_Server server;

  private Socket socket;

  private DataInputStream din;

  private DataOutputStream dout;

  private static String MF_ip = "localhost"; //"mainframe + /etc/hosts"
  private static int MF_port = 2222;
  
  private static String BDuser = "user";
  private static String BDpassword = "password";

  public ConnectionProcessor( EM_Server server, Socket socket ) {
    this.server = server;
    this.socket = socket;

    new Thread( this ).start();
  }
  
  public void run() {
    try {
      InputStream in = socket.getInputStream();
      OutputStream out = socket.getOutputStream();

      din = new DataInputStream( in );
      dout = new DataOutputStream( out );

   
      //Conexión con la base de datos
      
      String idExperiment = din.readUTF();
      String usuari = din.readUTF();
      String empresa = din.readUTF();
      String dades = din.readUTF();
      
      //TODO: Control de identidad.
      String dadesPath = idExperiment+usuari+empresa+".res";
      FileWriter fstream = new FileWriter(dadesPath);
      BufferedWriter bout = new BufferedWriter(fstream);
      while (!dades.equals("Fin!")){
	bout.write(dades);
	bout.newLine();
	dades = din.readUTF();
      }
      try {
	GestorBD gestorbd = new GestorBD();
        gestorbd.modificar("em", BDuser, BDpassword,
          "INSERT INTO em.EXPERIMENTS values (default, '"+idExperiment+"','"+usuari+"','"+empresa+"','"+dadesPath+"',' ','Pendent');");
        //Llamada al thread de comunicación con el MF.
	new EM_Client(MF_ip, MF_port);
	  }
      catch (Exception e){e.printStackTrace();}
      
    } catch( IOException ie ) {
      try {
        socket.close();
      } catch( IOException ie2 ) {
        System.out.println( "Error closing socket "+socket );
      }

      server.removeConnection( this );

      System.out.println( "Closed connection from socket "+socket );
    }
  }

}
